package com.trickytriad.tasks.ui
{
	import com.trickytriad.events.game.GetGamesOfPlayerEvent;
	import com.trickytriad.events.ui.ChangeMainViewEvent;
	import com.trickytriad.services.interfaces.I_GameService;
	import com.trickytriad.services.remote.GameServiceImpl_Remote;
	import com.trickytriad.util.Mask;
	
	import flash.events.Event;
	
	import org.spicefactory.lib.task.Task;

	/**
	 * Task that changes the main view state.  This includes 
	 * loading up any assets that need to be loaded for the state to be loaded.
	 */
	public class ChangeMainViewTask extends Task
	{
		// Viewstate index to switch
		private var _viewstateIndex:uint;
		// Callback function after task is complete
		private var _callback:Function;
				
		public var gameService:I_GameService;
		
		/**
		 * @param uint Viewstate index to switch to (ChangeMainViewEvent.<constants>)
		 * @param Function Callback function that will be called when this task is complete (optional)
		 */
		public function ChangeMainViewTask(in_vs:uint, in_callback:Function=null)
		{
			super();
			this._viewstateIndex = in_vs;
			this._callback = in_callback;
			gameService = new GameServiceImpl_Remote();		
		}
		
		/**
		 * Start function.  Puts up the loading screen, then does appropriate
		 * actions depending on the new view state.
		 */
		protected override function doStart():void
		{
			// Put the loading mask up
			Mask.show("Loading...");
			switch(_viewstateIndex)
			{
				case ChangeMainViewEvent.MAINVIEW_MAINMENU:
				{
					// Main menu, nothing to do.					
					onComplete(new Event(Event.COMPLETE));
					break;
				}	
				case ChangeMainViewEvent.MAINVIEW_GAMELIST:
				{					
					// Load up all of the player's games.
					gameService.setCallback(onGamelistComplete);
					gameService.getGamesOfPlayerFromServer(new GetGamesOfPlayerEvent(GetGamesOfPlayerEvent.GETGAMESOFPLAYER_REQUEST));				
				}
				default:
				{
					onComplete(new Event(Event.COMPLETE));
				}			
			}
		}
		
		/**
		 * Callback function for loading up the "Game List" view.
		 */ 
		public function onGamelistComplete (evt:GetGamesOfPlayerEvent) : void
		{
			Mask.close();
			// Create the result event
			var returnEvent:ChangeMainViewEvent = new ChangeMainViewEvent(ChangeMainViewEvent.CHANGEMAINVIEW_DONE, _viewstateIndex);
			returnEvent.gameList = evt._gameList;
			if (_callback != null)
				_callback(returnEvent);
			complete();
		}
		
		/**
		 * Function that is called when the task is finished.
		 */
		public function onComplete (evt:Event) : void
		{
			// Remove mask
			Mask.close();
			if (_callback != null)
				_callback(new ChangeMainViewEvent(ChangeMainViewEvent.CHANGEMAINVIEW_DONE, _viewstateIndex));
			complete();
		}
	}
}